<template>
  <div>
    <el-card class="box-card" shadow="hover">
      <div slot="header" class="clearfix">
        <span style="font-size: 18px">修改密码</span>
      </div>
      <el-form :model="pwdRuleForm" status-icon :rules="pwdRules" ref="pwdRuleForm" label-width="100px" class="demo-pwdRuleForm">
        <el-form-item label="原密码" prop="oldPwd">
          <el-input type="password" v-model="pwdRuleForm.oldPwd" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="新密码" prop="newPwd">
          <el-input type="password" v-model="pwdRuleForm.newPwd" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="确认新密码" prop="checkPass">
          <el-input type="password" v-model="pwdRuleForm.checkPass" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="submitPwdForm('pwdRuleForm')">提交</el-button>
          <el-button @click="resetForm('pwdRuleForm')">重置</el-button>
        </el-form-item>
      </el-form>
    </el-card>
    <br>
    <el-card class="box-card" shadow="hover">
      <div slot="header" class="clearfix">
        <span style="font-size: 18px">修改邮箱</span>
      </div>
      <el-form :model="emailRuleForm" status-icon :rules="emailRules" ref="emailRuleForm" label-width="100px" class="demo-pwdRuleForm">
        <el-form-item label="新邮箱地址" prop="email">
          <el-input type="email" v-model="emailRuleForm.email" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="验证码" prop="code">
          <el-input type="password" v-model="emailRuleForm.code" autocomplete="off"></el-input>
          <el-button
            @click="doSendCode"
            class="bind_code_gain"
            :disabled="sendObj.isSend"
          >{{ sendObj.sendCodeText }}
          </el-button
          >
        </el-form-item>

        <el-form-item>
          <el-button type="primary" @click="submitEmailForm('emailRuleForm')">提交</el-button>
          <el-button @click="resetForm('emailRuleForm')">重置</el-button>
        </el-form-item>
      </el-form>
    </el-card>
  </div>

</template>

<script>
import {changeEmail, changePwd, emailExist} from "../../api/user";
import {registerSendCode} from "../../api/login";

export default {
  data() {
    let validatePass = (rule, value, callback) => {
      if (value === '') {
        let field = '原密码'
        if (rule.field === 'newPwd') field = '新密码'
        callback(new Error(`请输入${field}`));
      } else {
        if (this.pwdRuleForm.checkPass !== '') {
          this.$refs.pwdRuleForm.validateField('checkPass');
        }
        callback();
      }
    };
    let validatePass2 = (rule, value, callback) => {
      if (value === '') {
        callback(new Error('请再次输入新密码'));
      } else if (value !== this.pwdRuleForm.newPwd) {
        callback(new Error('两次输入密码不一致!'));
      } else {
        callback();
      }
    };
    return {
      emailPattern: /^[a-zA-Z0-9_-]+@[a-zA-Z0-9_-]+(.[a-zA-Z0-9_-]+)+$/,
      pwdRuleForm: {
        oldPwd: '',
        newPwd: '',
        checkPass: '',
      },
      emailRuleForm: {
        email: '',
        tempToken: '',
        code: '',
      },
      sendObj: {
        sendInterval: 60,
        sendCodeText: '发送邮箱验证码',
        isSend: false,
        timer: null
      },
      emailRules: {
        email: [
          {required: true, message: '请输入邮箱地址', trigger: 'blur'},
          {type: 'email', message: '邮箱地址格式错误', trigger: 'blur'},
          {validator: this.validateEmail, trigger: 'blur'},
        ],
        code: [
          {required: true, message: '请输入验证码', trigger: 'blur'},
          {min: 6, max: 6, message: '请输入6位验证码', trigger: 'blur'}
        ],
      },
      pwdRules: {
        oldPwd: [
          {required: true, message: '原密码不能为空', trigger: 'blur'},
          {validator: validatePass, trigger: 'blur'}
        ],
        newPwd: [
          {required: true, message: '新密码不能为空', trigger: 'blur'},
          {validator: validatePass, trigger: 'blur'}
        ],
        checkPass: [
          {required: true, message: '确认密码不能为空', trigger: 'blur'},
          {validator: validatePass2, trigger: 'blur'}
        ]
      }
    };
  },
  methods: {
    submitPwdForm(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          changePwd(this.pwdRuleForm.oldPwd, this.pwdRuleForm.newPwd,this.$store.state.token).then(resp => {
            if (resp.success) {
              this.$message({type: 'success', message: '密码修改成功，请重新登录！', showClose: true})
              this.$store.dispatch('logout').then(() => {
                this.$router.push({path: '/'})
              })
            } else {
              this.$message({type: 'warning', message: '密码修改失败，请检查原密码是否输入有误！', showClose: true})
            }
          }).catch(err => {
            this.$message({type: 'warning', message: `密码修改失败，请检查原密码是否输入有误！`, showClose: true})
          })
        } else {
          this.$message({type: 'warning', message: '无法发起请求，请检查输入是否正确！', showClose: true})
          return false;
        }
      });
    },
    submitEmailForm(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          changeEmail(this.emailRuleForm, this.$store.state.token).then(resp => {
            if (resp.success) {
              this.$message({type: 'success', message: '邮箱修改成功', showClose: true})
              this.resetForm('emailRuleForm')
            } else {
              this.$message({type: 'success', message: '邮箱修改失败，邮箱可能已被占用', showClose: true})
            }
          }).catch(err => {
            this.$message({type: 'success', message: '邮箱修改失败，邮箱可能已被占用', showClose: true})
          })
        } else {
          this.$message({type: 'warning', message: '无法发起请求，请检查输入是否正确！', showClose: true})
          return false;
        }
      });
    },
    resetForm(formName) {
      this.$refs[formName].resetFields();
    },
    // 发送验证码
    async doSendCode() {
      if (this.emailRuleForm.email === '' || !this.emailPattern.test(this.emailRuleForm.email)) {
        this.$message({
          message: '邮箱为空或不符合邮箱规则',
          type: 'warning'
        })
        return
      }
      let resp1 = await emailExist(this.emailRuleForm.email)
      if (!resp1.success || resp1.data) {
        // 请求不成功或者邮箱重复
        this.$message({
          message: '邮箱已重复',
          type: 'warning'
        })
        return
      }
      let resp2 = await registerSendCode(this.emailRuleForm.email)
      if (!resp2.success || resp2.data === '') {
        this.$message({
          message: '验证码发送失败，可能是因为邮箱已重复',
          type: 'warning'
        })
        return
      }
      // 保存临时令牌
      this.emailRuleForm.tempToken = resp2.data
      this.sendObj.sendCodeText = this.sendObj.sendInterval
      this.sendObj.isSend = true
      clearInterval(this.sendObj.timer)
      this.sendObj.timer = setInterval(() => {
        if (this.sendObj.sendCodeText === 0) {
          clearInterval(this.sendObj.timer)
          this.sendObj.sendCodeText = '发送验证码'
          this.sendObj.isSend = false
          return
        }
        let time
        try {
          time = parseInt(this.sendObj.sendCodeText)
        } catch (e) {
          time = 60
        }
        this.sendObj.sendCodeText = time - 1
      }, 1000)
    },
    // 判断邮箱是否重复
    validateEmail(rule, value) {
      return new Promise((resolve, reject) => {
        emailExist(value).then(resp => {
          if (resp.success && !resp.data) {
            // 请求成功，并且未重复
            resolve()
          } else {
            reject('邮箱已重复')
          }
        })
      })
    }
  }
}
</script>

<style scoped>
.box-card {
  width: 98%;
  margin: 0 auto;
}

.bind_code_gain {
  border: 0;
  background: none;
  padding: 0 0 0 10px;
  border-radius: 0;
  position: absolute;
  top: calc(50% - 9px);
  right: 10px;
  font-size: 14px;
  line-height: 18px;
  cursor: pointer;
  border-left: 1px solid #d8d8d8;
}
</style>
